import {reactive,ref,unref,watch} from "vue";
import {Storage} from "hongshu-view";
import {parse} from "qs";

import EventBus from "~/tools/EventBus.js";

var router = null;
const CurNavigator = reactive({
    name:"",
    path:"",
});

const ListNavigator = ref([]);

/** 
 * 导航生成函数
 */
export default (r,menuList)=>{
    router = r;
    if(location.hash && location.hash.length > 2){
       let cacheNavigator =  Storage.get("hs-navigator");//缓存的导航
        // console.log(cacheNavigator)
        let curPath = getRoutePathByHash();//计算的导航
        // console.log(curPath)
        let defaultNavigator  = [getRouteInfo({
           path:curPath,
        },router.getRoutes(),menuList)];
        if(!cacheNavigator){
            ListNavigator.value = defaultNavigator;
        }else{
            if(cacheNavigator.length <= defaultNavigator.length){
                ListNavigator.value = defaultNavigator;
            }else{
                if(cacheNavigator[cacheNavigator.length -1].path == curPath){
                    ListNavigator.value = cacheNavigator;
                }else{
                    ListNavigator.value = defaultNavigator;
                };
            };
        };

        // 
    }
    window.addEventListener('hashchange', function() {
      
        EventBus.emit("ROUTER-BACK",-1);
    });


    routerListen(menuList);

    const RouterBack = ()=>{
        router && router.go(-1);
       
       
    };

    return {
        CurNavigator,
        RouterBack,
        ListNavigator,
    }
};

/**
 * 路由事件监听，更新导航条数据。别改
 * @param menuList 
 */
function routerListen(menuList){
  
    watch(ListNavigator,(val)=>{
        // console.log(val);
        Storage.set("hs-navigator",ListNavigator.value)
    },{
        deep:true
    })

    EventBus.on("ROUTER-PUSH",(param)=>{
        let target =  getRouteInfo(param,router.getRoutes(),menuList);
        if(!target.name){
            // throw new Error(`找不到路径${param.path}对应的路由名称`)
            console.warn(`找不到路径${param.path}对应的路由名称`)
            return;
        };
       let exist = ListNavigator.value.find((item)=>{
            return item.path == target.path;
        });
        if(!exist){
            ListNavigator.value.push(target);
        }
      
    });
    EventBus.on("ROUTER-REPLACE",(param)=>{
        let target =  getRouteInfo(param,router.getRoutes(),menuList);
        if(!target.name){
            // throw new Error(`找不到路径${param.path}对应的路由名称`)
            console.warn(`找不到路径${param.path}对应的路由名称`)
            return;
        };
        let targetIndex = ListNavigator.value.findIndex((item)=>{
             return item.path == target.path;
         });

         if(targetIndex == -1){
            ListNavigator.value[ListNavigator.value.length -1] = target;
         }
    });
    EventBus.on("ROUTER-RESET",(param)=>{
        let target =  getRouteInfo(param,router.getRoutes(),menuList);
        if(!target.name){
            // throw new Error(`找不到路径${param.path}对应的路由名称`)
            console.warn(`找不到路径${param.path}对应的路由名称`)
            return;
        };
        ListNavigator.value = [target];
    });
    EventBus.on("ROUTER-BACK",(param)=>{
        if(ListNavigator.value.length <= 1 ){
            let backPath = router.currentRoute.value.path;
            let target =  getRouteInfo({
                path:backPath,
                query:getQueryFormUrl(),
            },router.getRoutes(),menuList);
            ListNavigator.value[ListNavigator.value.length -1] = target;
        }else{
            ListNavigator.value.splice(ListNavigator.value.length -1,1);
        }
      
    });
    
    /** 确保刷新的时候加载正确的名称 */
    EventBus.on("ROUTER-UPDATE",()=>{
        if(location.hash && location.hash.length > 2){
            let target =  getRouteInfo({
                path:getRoutePathByHash(),
                query:getQueryFormUrl(),
              },router.getRoutes(),menuList);
            if(target){
                let targetIndex = ListNavigator.value.findIndex((item)=>{
                    return item.path == target.path;
                });
                if(targetIndex >-1){
                    ListNavigator.value[targetIndex].name= target.name;
                }
            }
             
        }
       
    });
};

/**
 * 从location.hash中提取路由，在初始化时，无法确保Router对象加载成功
 * @returns 过滤后的路由
 */
function getRoutePathByHash (){
    let pathWithQuery = location.hash.replace("#","");
    return pathWithQuery.split("?")[0];
}

function getQueryFormUrl(){
   let urlArr = location.href.split("?");
   if(urlArr.length <=1){
    return {};
   }else{
    return parse(urlArr[1]);
   }
}

/**
 * 通过路由更新名称
 * @param {*} target 
 */
export const UpdateNameByPath = (param)=>{
    let targetIndex = ListNavigator.value.findIndex((item)=>{
        return item.path == param.path;
    });
    if(targetIndex >-1){
        ListNavigator.value[targetIndex].name = param.name;
    }
}

/**
 * 更新当前路由的名称
 * @param {*} name 
 */
export const UpdateCurNavigatorName = (name)=>{
    if(ListNavigator.value.length > 0){
        ListNavigator.value[ListNavigator.value.length -1].name = name;
    }
};

/**
 * 获取路由信息通过
 * @param route 目标路由信息
 * @param routes 路由信息
 * @param menus 后台的菜单信息
 * @returns 
 */
function getRouteInfo(route,routes,menus){
    // debugger
    let path = route.path;
    let pathName = path.indexOf("/")== 0?path.substring(1):path;
    let result = {
        name:"",
        path,
    };

    routes.forEach((item)=>{
        if(item.path === path && item.meta){
            const {meta} = item;
            if(meta.renderName){
                if(!route.query){
                    route.query = {};
                }
                result.name = meta.renderName(route);
                return result;
            }else if(meta.name){
                result.name = meta.name;
                return result;
            }
        };
    });
    // console.log(result)
    if(result.name){
        return result;
    }
    //是否在后台返回的菜单中
    unref(menus).forEach((item)=>{
        // console.log(item)
        // console.log(pathName)
        if(item.child && item.child.length > 0){
            item.child.forEach((cItem)=>{
                if(cItem.url === pathName){
                    result.name = cItem.name;
                }
            });
        }else{
            if(item.url === pathName){
                result.name = item.name;
            }
        };
    });
    return result;
}
